package com.yangrong.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 阻塞队列实现两线程交替输出
 * @author Administrator
 *
 */
public class BlockingQueueCommunication {

	public static void main(String[] args) {
		final Business business = new Business();
		new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 1; i <= 50; i++) {
					business.sub(i);
				}
			}
		}).start();

		for (int i = 1; i <= 50; i++) {
			business.main(i);
		}
	}

	static class Business {
		BlockingQueue<Integer> queueMain = new ArrayBlockingQueue<Integer>(1);
		BlockingQueue<Integer> queueSub = new ArrayBlockingQueue<Integer>(1);

		{
			try {
				queueSub.put(1);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		public void sub(int i) {
			try {
				queueSub.put(1);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			for (int j = 1; j <= 5; j++) {
				System.out.println("sub thread sequence of " + j + ", loop of " + i);
			}

			try {
				queueMain.take();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		public void main(int i) {
			try {
				queueMain.put(1);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			for (int j = 1; j <= 10; j++) {
				System.out.println("main thread sequence of " + j + ", loop of " + i);
			}

			try {
				queueSub.take();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}